package com.linghang.lhonline.Util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class CookieUtil {


    public static void set(HttpServletResponse response,
                           String studentId,
                           String value,
                           int maxAge) {
        Cookie cookie = new Cookie(studentId, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static Cookie get(HttpServletRequest httpServletRequest,
                             String name) {

        Map<String, Cookie> map = readCookieMap(httpServletRequest);
        if (map.containsKey(name)) {
            return map.get(name);
        }
        return null;
    }

    private static Map<String, Cookie> readCookieMap(HttpServletRequest httpServletRequest) {

        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}

